<template>
  <section>
    <ul class="template-category-list">
      <li class="category-item" v-for="(category,cIndex) in categoryList" :key="cIndex" v-if="category.deleted =='UN_DELETED'">
        <a-popconfirm title="确定删除吗？" @confirm="onItemClose(cIndex)" @cancel="category.visible = false" okText="确定" cancelText="取消">
          <a class="category-close"><a-icon type="close-circle" /></a>
        </a-popconfirm>
        <div class="form-wrapper">
          <a-row>
            <a-col :span="7">
              <a-upload :showUploadList="false" :action="uploadAction" :beforeUpload="beforeUpload" @change="handleChange">
                <div @click="onUpClick(cIndex)" class="uploadbox">
                  <img v-if="category.imageUrl" :src="category.imageUrl" class="category-image"  />
                  <a-icon v-else type="cloud-upload" style="font-size:50px;color:#999"></a-icon>
                </div>
              </a-upload>
            </a-col>
            <a-col :span="16">
              <div class="form-row">
                <div class="form-item__label">分类排序</div>
                <div class="form-item__content">
                  <a-input-number size="small" style="width:50px" v-model="category.sort" :min="1" @change="onSortChange"></a-input-number>
                </div>
              </div>
              <div class="form-row">
                <div class="form-item__label">分类名称</div>
                <div class="form-item__content">
                  <a-input v-model="category.name" placeholder="(必填)"></a-input>
                </div>
              </div>
              <p class="default_tips">建议图片尺寸1比1，JPG、PNG格式，小于100KB</p>
            </a-col>
          </a-row>
          <div class="form-row">
            <div class="form-item__content">

            </div>
          </div>
          <div class="form-row">
            <div class="form-item__label">跳转链接</div>
            <div class="form-item__content">
              <a-input-group compact style="width:420px;">
                <a-select v-model="category.linkType" @change="onLinkChange(category,cIndex)"
                          placeholder="跳转类型" style="width:100px;">
                  <a-select-option :value="1">商品分类</a-select-option>
                  <a-select-option :value="2">自定义</a-select-option>
                </a-select>
                <a-input v-model="category.linkText" readOnly v-if="category.linkType === 1" @click.stop="handleSelect(category,cIndex)" style="width: 320px" placeholder="跳转到的页面" />
                <a-input v-model="category.linkUrl" v-else style="width: 320px" placeholder="跳转到的页面" />
              </a-input-group>
            </div>
          </div>
        </div>
      </li>
    </ul>
    <div>
      <a class="category-add" @click="onItemAdd">+创建分类</a>
    </div>
    <a-modal top="2vh" title="跳转链接" v-model="dialogVisible" :footer="null" width="800px" :maskClosable="false" @cancel="handleClose">
      <select-category @result="emitSave" :selected-key="dialogKey" v-if="dialogVisible"></select-category>
    </a-modal>
  </section>
</template>

<script>
import SelectCategory from './SelectCategory'
  export default {
    name: "Category",
    props:{
      categorys:{
        type:Array,
        default:()=>{return []}
      }
    },
    components:{ SelectCategory },
    data(){
      return{
        categoryList:[],
        template:{
          id:null,
          categoryId:null,
          sort:1,
          name:'',
          imageUrl:'',
          linkUrl:'',
          linkType:2,
          linkText:'',
          visible:false,
          deleted:'UN_DELETED',
        },
        uploadIndex:-1,
        uploadAction:this.UPLOAD_URL,
        dialogVisible:false,
        dialogKey: null
      }
    },
    watch:{
      categoryList:function (value,oldValue) {
        this.autoUpdate();
      }
    },
    methods: {
      onItemClose(index){
        this.categoryList[index].visible = false;
        if(this.categoryList[index].id != null){
          this.categoryList[index].deleted = 'DELETED';
        }else {
          this.categoryList.splice(index, 1)
        }
      },
      onItemAdd() {
        let newCategory = {...this.template};
        let list = this.categoryList.filter(m=>m.deleted=='UN_DELETED') || [];
        let maxSort = list.length>0?list[list.length-1].sort : 0;
        newCategory.sort = maxSort + 1;
        this.categoryList.push(newCategory)
        // this.autoUpdate();
      },
      handleSelect(banner,index){
        if(banner.linkType === 1){
          this.uploadIndex = index
          this.dialogKey = banner.categoryId
          this.dialogVisible = true
        }
      },
      handleClose(){
        this.uploadIndex = -1;
        this.dialogVisible = false;
      },
      onLinkChange(category,index){
        switch (category.linkType) {
          case 1://选择书库分类
            category.linkUrl = '';
            this.uploadIndex = index;
            this.dialogVisible = true;
            break;
          case 2://自定义
            category.categoryId = '';
            break;
        }
      },
      emitSave(category){
        this.dialogVisible = false;
        let editCategory =  this.categoryList[this.uploadIndex];
        if(category!=null){
          editCategory.categoryId = category.id;
          // if(this.baseUtil.isBlank(editCategory.imageUrl)) editCategory.imageUrl=category.imageUrl;
          if(this.baseUtil.isBlank(editCategory.name)) editCategory.name = category.name;
          editCategory.linkText = category.name;
        }else{
          editCategory.linkType = 2;
        }
        this.uploadIndex = -1;
        // this.autoUpdate();
      },
      onSortChange(){
        this.categoryList.sort((a,b)=>{ return a.sort - b.sort})
      },
      onUpClick(index){
        console.log('upload---->',index)
        this.uploadIndex = index;
      },
      beforeUpload(file, fileList){
        this.loading = true
        const isJPG = file.type === 'image/jpeg';
        const isPNG = file.type === 'image/png';
        const isGif = file.type === 'image/gif';
        if (!isJPG && !isPNG && !isGif) {
          this.$message.error('图片格式错误,请检查后重新上传!');
          this.loading = false;
          return false;
        }
        const isLt500KB = file.size / 1024 / 500
        if (!isLt500KB) {
          this.$message.error('图片大小不合适,请上传小于500KB的图片!');
          this.loading = false;
          return false;
        }
        return true;
      },
      handleChange({file, fileList}) {
        console.log('---change>', file, fileList)
        if(file.status === 'error'){
          this.loading = false;
          return;
        }
        else if(file.status === 'done') {
          // 根据服务端返回数据筛选上传成功的文件
          if (file.response) {
            this.categoryList[this.uploadIndex].imageUrl = file.response.data;
            this.uploadIndex = -1;
            console.log('-----ok>', this.categoryList)
          }
          this.loading = false;
        }
      },
      autoUpdate(){
        this.$emit("update:categorys",this.categoryList)
      }
    },
    mounted(){
      let categoryList = this.categorys || []

      if(categoryList.length > 0){
        categoryList.map(m=>{
          m.linkText = m.name
        })
        this.categoryList = categoryList;
      }else{
        this.categoryList = categoryList;
        this.onItemAdd();
      }
    }
  }
</script>

<style scoped>
  .form-wrapper{
    display: block;
  }
  .form-row{
    display: flex;
    line-height: 36px;
    margin-bottom:10px;
  }
  .form-row .form-item__label{
    flex-grow: 0;
    width:80px;
    font-size:14px;
    font-weight: bolder;
    color:#666;
  }
  .form-row .form-item__content{
    flex-grow: 1;
    text-align: left;
  }
  .uploadbox {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    text-align: center;
    width:120px;
    height:120px;
    line-height: 2;
  }
  .uploadbox:hover {
    border-color: #409EFF;
  }
  .template-category-list,.template-category-list li{ list-style:none; margin:0;padding:0;}
  .template-category-list{
    width:500px;
  }
  .category-item{
    position: relative;
  }
  .category-close{
    position: absolute;
    z-index: 1001;
    right:0px;
    top:0px;
    cursor: pointer;
    font-size: 16px;
    width:16px;
    height:16px;
    color:#555;
  }
  .category-close:hover{
    color:#333;
  }
  .category-item .default_tips{
    margin:0;
    padding:0 0 10px 0;
    line-height: normal;
  }
  .category-uploader{
    margin-bottom:16px;
  }
  .category-uploader-icon {
    margin:0 auto;
    font-size: 50px;
    color: #8c939d;
    text-align: center;
    line-height: 108px;
  }
  .category-image {
    width: 120px;
    height: 120px;
    display: block;
  }
  .category-add{
    cursor: pointer;
    font-size:13px;
    font-weight: bolder;
    color:#37BCA0;
  }
</style>
